package com.he.controller;

import com.he.entity.CommonResult;
import com.he.entity.User;
import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.sql.SQLException;

@RestController
public class UserController {
    @Resource
    private RestTemplate restTemplate;

    private static final String REST_URL_PREFIX = "http://SPRINGCLOUD-PROVIDER";

    @GetMapping("/user/getUserById/{userId}")
    @CircuitBreaker(name = "backendA",fallbackMethod = "getUserByIdDown")
    public CommonResult<User> getProviderUser(@PathVariable("userId") Integer userId) {
        User user =new User();
        CommonResult<User> userCommonResult = new CommonResult<>();
        try {
            user = restTemplate.getForObject(REST_URL_PREFIX + "/user/getUserById/" + userId, User.class);
            System.out.println(user);
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonResult<>(500, "错误", null);
        }
        return new CommonResult<User>(200, "成功", user);
    }

    /**
     * getProviderUser的服务降级方法，输入和返回值必须相同
     * @param userId
     * @return
     */
    public CommonResult<User> getUserByIdDown(Integer userId,Throwable e){
        System.out.println("获取用户ID"+userId+"的服务被熔断，方法降级");
        System.out.println(e);
        return new CommonResult<>(500,"哎哟出错啦",new User(userId,""));
    }

    public CommonResult<User> getUserByIdDown(Integer userId, SQLException e){
        System.out.println("获取用户ID"+userId+"的服务被熔断，方法降级"+"请联系管理员");
        System.out.println(e);
        return new CommonResult<>(500,"哎哟出错啦",new User(userId,""));
    }
}
